package com.hafu.swing;

import com.hafu.model.Teacher;
import com.hafu.service.TeacherService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

// 教师管理面板
public class TeacherManagePanel extends JPanel {
    private TeacherService teacherService;
    private JTable teacherTable;
    private DefaultTableModel tableModel;

    public TeacherManagePanel(JPanel parentPanel, TeacherService teacherService) {
        this.teacherService = teacherService;
        setLayout(new BorderLayout());

        // 顶部工具栏
        JPanel toolbarPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton addButton = new JButton("添加教师");
        JButton editButton = new JButton("编辑教师");
        JButton deleteButton = new JButton("删除教师");
        JButton refreshButton = new JButton("刷新");
        JTextField searchField = new JTextField(15);
        JButton searchButton = new JButton("搜索");

        toolbarPanel.add(addButton);
        toolbarPanel.add(editButton);
        toolbarPanel.add(deleteButton);
        toolbarPanel.add(new JSeparator(SwingConstants.VERTICAL));
        toolbarPanel.add(new JLabel("工号/姓名:"));
        toolbarPanel.add(searchField);
        toolbarPanel.add(searchButton);
        toolbarPanel.add(refreshButton);

        // 表格数据
        String[] columnNames = {"工号", "姓名", "性别", "年龄", "职称", "所属院系", "联系电话", "操作"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 7; // 只允许编辑最后一列(操作)
            }
        };
        teacherTable = new JTable(tableModel);
        teacherTable.setRowHeight(30);
        teacherTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        teacherTable.getColumnModel().getColumn(1).setPreferredWidth(80);
        teacherTable.getColumnModel().getColumn(2).setPreferredWidth(40);
        teacherTable.getColumnModel().getColumn(3).setPreferredWidth(40);
        teacherTable.getColumnModel().getColumn(4).setPreferredWidth(80);
        teacherTable.getColumnModel().getColumn(5).setPreferredWidth(100);
        teacherTable.getColumnModel().getColumn(6).setPreferredWidth(100);
        teacherTable.getColumnModel().getColumn(7).setPreferredWidth(100);

        JScrollPane scrollPane = new JScrollPane(teacherTable);

        // 加载教师数据
        loadTeacherData();

        // 添加按钮事件
        addButton.addActionListener(e -> {
            JFrame parentFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
            new AddTeacherDialog(parentFrame, teacherService).setVisible(true);
        });

        // 编辑按钮事件
        editButton.addActionListener(e -> {
            int selectedRow = teacherTable.getSelectedRow();
            if (selectedRow >= 0) {
                String teacherId = (String) tableModel.getValueAt(selectedRow, 0);
                new EditTeacherDialog(this, teacherService, teacherId).setVisible(true);
            } else {
                JOptionPane.showMessageDialog(this, "请先选择要编辑的教师", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 删除按钮事件
        deleteButton.addActionListener(e -> {
            int selectedRow = teacherTable.getSelectedRow();
            if (selectedRow >= 0) {
                String teacherId = (String) tableModel.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定要删除工号为" + teacherId + "的教师吗?", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    if (teacherService.deleteTeacher(teacherId)) {
                        JOptionPane.showMessageDialog(this, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                        loadTeacherData();
                    } else {
                        JOptionPane.showMessageDialog(this, "删除失败", "失败", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请先选择要删除的教师", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 搜索按钮事件
        searchButton.addActionListener(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                searchTeachers(keyword);
            } else {
                loadTeacherData();
            }
        });

        // 刷新按钮事件
        refreshButton.addActionListener(e -> loadTeacherData());

        add(toolbarPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
    }

    // 加载教师数据（修复空指针异常）
    private void loadTeacherData() {
        // 检查 tableModel 是否为 null
        if (tableModel == null) {
            System.out.println("[警告] tableModel 为 null，无法加载数据");
            return;
        }

        tableModel.setRowCount(0);

        // 检查 teacherService 是否为 null
        if (teacherService == null) {
            System.out.println("[警告] teacherService 为 null，无法获取教师数据");
            return;
        }

        List<Teacher> teachers = teacherService.getAllTeachers();

        // 检查 teachers 列表是否为 null
        if (teachers == null) {
            System.out.println("[警告] teacherService.getAllTeachers() 返回 null，改用空列表");
            teachers = new ArrayList<>();
        }

        System.out.println("[TeacherManagePanel] 共获取 " + teachers.size() + " 条教师数据");

        for (int i = 0; i < teachers.size(); i++) {
            Teacher teacher = teachers.get(i);

            // 打印教师信息（用于调试）
            System.out.println("[加载教师 #" + (i + 1) + "] " + teacher);

            // 检查 teacher 对象是否为 null
            if (teacher == null) {
                System.out.println("[警告] 教师对象为 null，跳过该条数据");
                continue;
            }

            // 检查教师ID是否为 null
            if (teacher.getTeacherId() == null) {
                System.out.println("[警告] 教师ID为null，跳过该条数据");
                continue;
            }

            // 为每个属性添加空值检查
            Object[] rowData = {
                    teacher.getTeacherId(),
                    teacher.getName() != null ? teacher.getName() : "（姓名为空）",
                    teacher.getGender() != null ? teacher.getGender() : "（性别为空）",
                    teacher.getAge() != null ? teacher.getAge() : 0,
                    teacher.getTitle() != null ? teacher.getTitle() : "（职称为空）",
                    teacher.getDepartment() != null ? teacher.getDepartment() : "（所属院系为空）",
                    teacher.getPhone() != null ? teacher.getPhone() : "（联系电话为空）",
                    "查看详情"
            };
            tableModel.addRow(rowData);
        }
    }

    // 搜索教师（添加空值检查）
    private void searchTeachers(String keyword) {
        if (tableModel == null) {
            System.out.println("[警告] tableModel 为 null，无法搜索数据");
            return;
        }

        if (teacherService == null) {
            System.out.println("[警告] teacherService 为 null，无法搜索教师数据");
            return;
        }

        tableModel.setRowCount(0);
        List<Teacher> teachers = teacherService.searchTeachers(keyword);

        if (teachers == null) {
            System.out.println("[警告] teacherService.searchTeachers() 返回 null，改用空列表");
            teachers = new ArrayList<>();
        }

        for (Teacher teacher : teachers) {
            if (teacher == null) {
                System.out.println("[警告] 教师对象为 null，跳过该条数据");
                continue;
            }

            Object[] rowData = {
                    teacher.getTeacherId() != null ? teacher.getTeacherId() : "（工号为空）",
                    teacher.getName() != null ? teacher.getName() : "（姓名为空）",
                    teacher.getGender() != null ? teacher.getGender() : "（性别为空）",
                    teacher.getAge() != null ? teacher.getAge() : 0,
                    teacher.getTitle() != null ? teacher.getTitle() : "（职称为空）",
                    teacher.getDepartment() != null ? teacher.getDepartment() : "（所属院系为空）",
                    teacher.getPhone() != null ? teacher.getPhone() : "（联系电话为空）",
                    "查看详情"
            };
            tableModel.addRow(rowData);
        }
    }

    // 刷新数据
    public void refreshData() {
        loadTeacherData();
    }
}